package cn.com.nes.site.module.service;

import cn.com.nes.common.util.Globals;
import cn.com.nes.common.util.OssUtil;
import cn.com.nes.common.util.ParameterUtil;
import cn.com.nes.mybatis.callcenter.entity.CcUser;
import cn.com.nes.mybatis.callcenter.entity.CompanyApplyRecord;
import cn.com.nes.mybatis.callcenter.mapper.CcUserMapper;
import cn.com.nes.mybatis.callcenter.mapper.CompanyApplyRecordMapper;
import cn.com.nes.site.entity.DataReq;
import cn.com.nes.site.entity.PageData;
import cn.com.nes.site.entity.em.DeleteEnum;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Service
public class CallCenterApplyService {

    @Resource
    private CompanyApplyRecordMapper companyApplyRecordMapper;

    @Resource
    private CcUserMapper ccUserMapper;

    public PageData getCallCenterApply(DataReq req) throws Exception {
        PageData res = new PageData();
        res.setRetCode(1);
        res.setRetMessage("查询失败");
        String agentCompanyId = ParameterUtil.getString(req, "agentCompanyId");
        CompanyApplyRecord query = new CompanyApplyRecord();
        query.setAgentCompanyId(agentCompanyId);
        query.setDeleted(0);
        LambdaQueryWrapper<CompanyApplyRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CompanyApplyRecord::getAgentCompanyId, agentCompanyId);
        queryWrapper.eq(CompanyApplyRecord::getDeleted, DeleteEnum._0.getKey());
        CompanyApplyRecord companyApply = companyApplyRecordMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNotNull(companyApply)) {
            companyApply.setOrderTakingAbilitys(StrUtil.isNotEmpty(companyApply.getOrderTakingAbility()) ? Arrays
                    .asList(companyApply.getOrderTakingAbility().split(";")) : new ArrayList<>());
            companyApply.setOrderDispatchingWays(StrUtil.isNotEmpty(companyApply.getOrderDispatchingWay()) ? Arrays
                    .asList(companyApply.getOrderDispatchingWay().split(";")) : new ArrayList<>());
            companyApply.setServiceProcessRecords(StrUtil.isNotEmpty(companyApply.getServiceProcessRecord()) ? Arrays
                    .asList(companyApply.getServiceProcessRecord().split(";")) : new ArrayList<>());
            companyApply.setEquipmentCompanyIdList(StrUtil.isNotEmpty(companyApply.getEquipmentCompanyIds()) ? Arrays
                    .asList(companyApply.getEquipmentCompanyIds().split(";")) : new ArrayList<>());
            if (StrUtil.isNotEmpty(companyApply.getPicDisplay())) {
                List<String> list = Arrays.asList(companyApply.getPicDisplay().split(";"));
                if (CollUtil.isNotEmpty(list)) {
                    List<String> urls = new ArrayList<>();
                    for (String s : list) {
                        String imgSignPublicURL = OssUtil.getImgSignURL(s, 1, Globals.bucketName_call);
                        urls.add(imgSignPublicURL);
                    }
                    companyApply.setPicDisplays(urls);
                }
            } else {
                companyApply.setPicDisplays(new ArrayList<>());
            }
            companyApply.setTerritorys(StrUtil.isNotEmpty(companyApply.getTerritory()) ? Arrays.asList(companyApply
                    .getTerritory()
                    .split(";")) : new ArrayList<>());
            HashMap<String, Object> map = new HashMap<>();
            map.put("companyApplication", companyApply);
            res.setData(map);
            res.setRetCode(0);
            res.setRetMessage("查询成功");
            return res;
        }
        res.setRetCode(0);
        res.setRetMessage("未查询到数据");
        return res;
    }

    @Transactional(rollbackFor = Exception.class)
    public PageData saveCallCenterApply(DataReq req) throws Exception {
        PageData res = new PageData();
        res.setRetCode(1);
        res.setRetMessage("申请失败");
        Long id = ParameterUtil.getLong(req, "id");
        String agentCompanyId = ParameterUtil.getString(req, "agentCompanyId"); // 热链云公司ID
        Long companyId = ParameterUtil.getLong(req, "companyId"); // 长效管护客服中心公司ID
        String xzqhdm = ParameterUtil.getString(req, "xzqhdm"); // 行政区划代码
        String companyName = ParameterUtil.getString(req, "companyName"); // 客服中心公司名称
        String address = ParameterUtil.getString(req, "address"); // 服务中心地址
        String phone = ParameterUtil.getString(req, "phone"); // 服务中心热线电话
        String operatingCompany = ParameterUtil.getString(req, "operatingCompany"); // 服务中心运营单位
        String leader = ParameterUtil.getString(req, "leader"); // 负责人
        String leaderPhone = ParameterUtil.getString(req, "leaderPhone"); // 负责人电话
        Date establishedDate = ParameterUtil.getDate(req, "establishedDate"); // 运营中心成立时间 格式yyyy-MM-dd
        String orderTakingAbility = ParameterUtil.getJSONArrayToSplitStr(req, "orderTakingAbility", ";"); // 接单能力
        String orderDispatchingWay = ParameterUtil.getJSONArrayToSplitStr(req, "orderDispatchingWay", ";"); // 派单方式
        String serviceProcessRecord = ParameterUtil.getJSONArrayToSplitStr(req, "serviceProcessRecord", ";"); // 服务过程记录
        String picDisplay = ParameterUtil.getString(req, "picDisplay"); // 服务中心面貌展示
        String territory = ParameterUtil.getJSONArrayToSplitStr(req, "territory", ";"); // 服务中心服务范围
        String remarks = ParameterUtil.getString(req, "remarks"); // 服务中心简介
        BigDecimal longitude = ParameterUtil.getDecimal(req, "longitude"); // 经度
        BigDecimal latitude = ParameterUtil.getDecimal(req, "latitude"); // 纬度
        Integer callPopupPattern = ParameterUtil.getInteger(req, "callPopupPattern");// 弹屏模式  0本地模式  1远程模式
        String companyType = ParameterUtil.getString(req, "companyType"); // 客服中心类型
        String adminAccount = ParameterUtil.getString(req, "adminAccount"); // 管理员账号
        String legalPerson = ParameterUtil.getString(req, "legalPerson"); // 企业法人
        String businessScope = ParameterUtil.getString(req, "businessScope"); // 经营范围
        Integer isAllEquipmentCompany = ParameterUtil.getInteger(req, "isAllEquipmentCompany"); // 是否负责所有品牌：1所有品牌，0查询company_equipment_company表
        String equipmentCompanyIds = ParameterUtil.getJSONArrayToSplitStr(req, "equipmentCompanyIds",";"); // 公司负责品牌（设备厂家ID），可多个
        Integer equipmentGuaranteeStatus = ParameterUtil.getInteger(req, "equipmentGuaranteeStatus"); // 公司负责的设备是否在质保：0全部，1质保，2出保
        Integer isEquipmentGdgq = ParameterUtil.getInteger(req, "isEquipmentGdgq"); // 公司负责的设备：0所有，1煤改电，2煤改气
        Integer isEquipmentMyself = ParameterUtil.getInteger(req, "isEquipmentMyself"); // 是否负责自己的设备：0所有，1自己添加的设备
        String gsdm = ParameterUtil.getString(req, "gsdm"); // 公司代码
        Integer isApplication = ParameterUtil.getInteger(req, "isApplication"); // 是否是“申请试用”公司  0 不是  1 是
        CompanyApplyRecord companyApplyRecord;

        // 2024-12-03 项目组决定加一个账号重复的提示
        LambdaQueryWrapper<CcUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CcUser::getAccount, adminAccount);
        queryWrapper.eq(CcUser::getIsDelete, DeleteEnum._0.getKey());
        Integer i = ccUserMapper.selectCount(queryWrapper);
        if (i > 1) {
            res.setRetCode(1);
            res.setRetMessage("管理员账号已存在");
            return res;
        }

        // 这个sql会抛出 TooManyResultsException 异常
        CcUser ccUser = ccUserMapper.selectByAccout(adminAccount);
        if (ObjectUtil.isNotNull(ccUser)) {
            res.setRetCode(1);
            res.setRetMessage("管理员账号已存在");
            return res;
        }

        if (ObjectUtil.isNull(id)) {
            companyApplyRecord = new CompanyApplyRecord();
            CompanyApplyRecord query = new CompanyApplyRecord();
            query.setAgentCompanyId(agentCompanyId);
            query.setDeleted(0);
            LambdaQueryWrapper<CompanyApplyRecord> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(CompanyApplyRecord::getAgentCompanyId, agentCompanyId);
            queryWrapper1.eq(CompanyApplyRecord::getDeleted, DeleteEnum._0.getKey());
            CompanyApplyRecord companyApplication1 = companyApplyRecordMapper.selectOne(queryWrapper1);
            if (ObjectUtil.isNotNull(companyApplication1)) {
                res.setRetCode(1);
                res.setRetMessage("已申请，不能重复申请！");
                return res;
            }

        } else {
            companyApplyRecord = companyApplyRecordMapper.selectById(id);
            if (ObjectUtil.isNotNull(companyApplyRecord.getCheckState()) && 2 != companyApplyRecord.getCheckState()) {
                res.setRetCode(1);
                res.setRetMessage("当前申请未审核或已通过，不能修改！");
                return res;
            }
        }

        companyApplyRecord.setAgentCompanyId(agentCompanyId);
        companyApplyRecord.setCompanyId(companyId);
        companyApplyRecord.setXzqhdm(xzqhdm);
        companyApplyRecord.setCompanyName(companyName);
        companyApplyRecord.setAddress(address);
        companyApplyRecord.setPhone(phone);
        companyApplyRecord.setOperatingCompany(operatingCompany);
        companyApplyRecord.setLeader(leader);
        companyApplyRecord.setLeaderPhone(leaderPhone);
        companyApplyRecord.setEstablishedDate(establishedDate);
        companyApplyRecord.setOrderTakingAbility(orderTakingAbility);
        companyApplyRecord.setOrderDispatchingWay(orderDispatchingWay);
        companyApplyRecord.setServiceProcessRecord(serviceProcessRecord);
        companyApplyRecord.setPicDisplay(picDisplay);
        companyApplyRecord.setTerritory(territory.replaceAll("\"","").replace(",", ";").replace("[", "").replace("]", ""));
        companyApplyRecord.setRemarks(remarks);
        companyApplyRecord.setLongitude(longitude);
        companyApplyRecord.setLatitude(latitude);
        companyApplyRecord.setCallPopupPattern(callPopupPattern);
        companyApplyRecord.setCompanyType(companyType);
        companyApplyRecord.setAdminAccount(adminAccount);
        companyApplyRecord.setLegalPerson(legalPerson);
        companyApplyRecord.setBusinessScope(businessScope);
        companyApplyRecord.setIsAllEquipmentCompany(isAllEquipmentCompany);
        companyApplyRecord.setEquipmentCompanyIds(equipmentCompanyIds);
        companyApplyRecord.setEquipmentGuaranteeStatus(equipmentGuaranteeStatus);
        companyApplyRecord.setIsEquipmentGdgq(isEquipmentGdgq);
        companyApplyRecord.setIsEquipmentMyself(isEquipmentMyself);
        companyApplyRecord.setGsdm(StrUtil.isNotBlank(gsdm) ? gsdm : agentCompanyId);
        companyApplyRecord.setIsApplication(isApplication);
        companyApplyRecord.setGmtCreate(new Date());

        if (ObjectUtil.isNull(id)) {
            companyApplyRecordMapper.insert(companyApplyRecord);
            res.setRetCode(0);
            res.setRetMessage("申请成功");
        } else {
            companyApplyRecord.setId(id);
            companyApplyRecord.setCheckState(0);
            companyApplyRecord.setGmtModified(new Date());
            companyApplyRecordMapper.updateById(companyApplyRecord);
            res.setRetCode(0);
            res.setRetMessage("申请修改成功");
        }

        return res;
    }


    public static void main(String[] args) {
        String str = "[\"11\",\"110100000000\",\"110114000000\",\"110114115000\"]";

        str = str.replaceAll("\"","").replace(",", ";").replace("[", "").replace("]", "");
        System.out.println(str);
    }

}
